﻿Imports TyranntEngine
Imports System.IO
Imports System.Threading

Public Class updaterForm

    Private _jobList As GameFileCollection
    Private _totalSize As Long = 0
    Private WithEvents _client As New TyranntWelcomeService.WelcomeClient
    Private WithEvents Worker As New System.ComponentModel.BackgroundWorker
    Private cancelled As Boolean = False

    Public Sub New(ByVal JobList As GameFileCollection)
        Me.InitializeComponent()
        _jobList = JobList
        For Each job As GameFile In _jobList
            _totalSize += job.Size
        Next
        totalProgressBar.Maximum = CInt(_totalSize)
    End Sub

    Private Sub updaterForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Worker.WorkerReportsProgress = True
        Worker.WorkerSupportsCancellation = True
        Worker.RunWorkerAsync()
    End Sub

    Private Sub TestWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles Worker.DoWork
        For Each job As GameFile In _jobList
            If job.Action = "download" Then
                Worker.ReportProgress(0, "0" + Chr(254) + "Downloading " + job.Filename)
                Dim fs As Stream = _client.GetFile(job.Filename)
                Dim sw As New FileStream(".\" + job.Filename, FileMode.Create)
                Dim bw As New BinaryWriter(sw)
                Dim b As Integer
                Do
                    If Worker.CancellationPending = True Then
                        Exit Sub
                    End If
                    b = fs.ReadByte()
                    If b = -1 Then
                        Exit Do
                    End If
                    bw.Write(CByte(b))
                Loop
                sw.Close()
                Worker.ReportProgress(0, job.Size.ToString + Chr(254) + "Downloading " + job.Filename)
            End If
            If Worker.CancellationPending = True Then
                Exit Sub
            End If
        Next
    End Sub

    Private Sub TestWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles Worker.ProgressChanged
        Dim bits() As String = e.UserState.ToString.Split(Chr(254))
        Dim bytesSoFar As Integer
        If Integer.TryParse(bits(0), bytesSoFar) Then
            totalProgressBar.Value += bytesSoFar
        End If
        actionLabel.Text = bits(1)
    End Sub

    Private Sub Worker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles Worker.RunWorkerCompleted
        If cancelled = True Then
            End
        End If
        Me.Close()
    End Sub

    Private Sub exitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exitButton.Click
        Worker.CancelAsync()
        cancelled = True
    End Sub
End Class
